package perform.database;

import perform.mappings.ClassMappings;
import perform.mappings.ManyToManyMapping;

public class ManyToManyProcessor {
	
	private ManyToManyMapping mapping;
	
	private boolean existed;
	private String createQuery;

	public ManyToManyProcessor(ManyToManyMapping mapping) {
		this.mapping = mapping;
		ColumnProcessor column1 = mapping.getIdColumn1();
		ColumnProcessor column2 = mapping.getIdColumn2();
		StringBuilder builder = new StringBuilder("create table `").append(mapping.getName()).append("` (\n");
		builder.append("\t`").append(mapping.getColumn1()).append("` ").append(buildColumn(column1));
		builder.append("\t`").append(mapping.getColumn2()).append("` ").append(buildColumn(column2));
		builder.append("\tprimary key ( `").append(mapping.getColumn1()).append("` , `").append(mapping.getColumn2()).append("` ) ,\n");
		builder.append("\tforeign key ( `").append(mapping.getColumn1()).append("` ) references `")
				.append(ClassMappings.getTable(mapping.getClass1())).append("` ( `")
				.append(column1.getName()).append("` ) on update cascade on delete cascade ,\n");
		builder.append("\tforeign key ( `").append(mapping.getColumn2()).append("` ) references `")
				.append(ClassMappings.getTable(mapping.getClass2())).append("` ( `")
				.append(column2.getName()).append("` ) on update cascade on delete cascade \n) engine = InnoDB ;");
		createQuery = builder.toString();
	}
	
	private String buildColumn(ColumnProcessor processor){
		if(processor.getLength() > 0 && processor.getPrecision() > 0){
			return processor.getType() + " (" + processor.getLength() + "," + processor.getPrecision() + ") not null ,\n";
		} else if(processor.getLength() > 0){
			return processor.getType() + " (" + processor.getLength() + ") not null ,\n";
		} else {
			return processor.getType() + " not null ,\n";
		}
	}
	
	public String getName(){
		return mapping.getName();
	}
	public ManyToManyMapping getMapping() {
		return mapping;
	}
	public String getCreateQuery() {
		return createQuery;
	}
	public boolean isExisted() {
		return existed;
	}
	public void setExisted(boolean existed) {
		this.existed = existed;
	}
	
}
